<link rel="stylesheet" href="/stylesheets/admin.css">
<link rel="stylesheet" href="/stylesheets/style.css">
<link href="/multiselect/css/multi-select.css" media="screen" rel="stylesheet" type="text/css">

<style>

</style>
<div class="row">
    <div class="col-xs-12">
        <div class="container-header">
            <p class="container-title"><%= platform %> 模块管理</p>
        </div>
        <div class="setting-div">
            <div class="setting-header-div">
                <div>
                    <% if (type === 1 ) {  %>
                    <button id="create-btn" class="create-btn btn btn-default">添加模块</button>
                    <% } else if (type === 2 ) { %>
                    <button disabled id="create-btn" class="create-btn btn btn-default">添加模块(暂未开通)</button>
                    <% } %>

                    <% if (type === 1 && user.role && user.role.permissions.managerA) {  %>
                    <a href="/component?platform=android" id="create-btn" class="list-header-btn btn btn-default">切换到 Android</a>
                    <% } else if (type === 2 && user.role && user.role.permissions.managerI) { %>
                    <a href="/component?platform=ios" id="create-btn" class="list-header-btn btn btn-default">切换到 iOS</a>
                    <% } %>
                </div>
                <hr>
            </div>
            <div>
                <table class="table table-striped">
                    <thead>
                    <tr>
                        <th>模块名字</th>
                        <th>版本</th>
                        <th>Repo</th>
                        <th>上次升级时间</th>
                        <th>上次升级用户</th>
                        <th>上次升级结果</th>
                        <th>平均耗时</th>
                        <th>通知机器人</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="list-body">
                    </tbody>
                </table>
            </div>
            <div class="setting-footer-div">

            </div>
        </div>
        <div style="height: 40px"></div>
    </div>
</div>
<!-- 模态框（Modal） -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel">添加模块</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" role="form">
                    <div class="form-group">
                        <label for="name" class="col-sm-3 control-label">名称</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control" id="name" placeholder="请输入模块名称">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="version" class="col-sm-3 control-label">版本</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control" id="version" placeholder="请输入模块当前版本">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="url" class="col-sm-3 control-label">Git地址</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control" id="url" placeholder="请输入仓库地址">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="gituser" class="col-sm-3 control-label">Git用户</label>
                        <div class="col-sm-9">
                            <select class="form-control" name="gituser" id="gituser">
                                <% if (gitusers && gitusers.length) { %>
                                <option value="">不使用</option>
                                <% gitusers.forEach(function(gituser){ %>
                                <option value=<%= gituser._id%>><%= gituser.name%></option>
                                <% }) %>
                                <% } else { %>
                                <option value="">不使用</option>
                                <% } %>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="repo" class="col-sm-3 control-label">Repo</label>
                        <div class="col-sm-9">
                            <select class="form-control" name="repo" id="repo">
                                <% if (repos && repos.length) { %>
                                <% repos.forEach(function(repo){ %>
                                <option value=<%= repo._id%>><%= repo.name%></option>
                                <% }) %>
                                <% } else { %>
                                <option value="">暂不可选项</option>
                                <% } %>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="role" class="col-sm-3 control-label">通知机器人</label>
                        <div class="col-sm-9">
                            <select multiple="multiple" class="form-control" id="robots">
                                <% if (robots && robots.length > 0) { %>
                                <% robots.forEach(function(robot){ %>
                                <option value=<%= robot._id%>><%= robot.name%></option>
                                <% }) %>
                                <% } else { %>
                                <option value="" disabled>无可选机器人</option>
                                <% } %>
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" id="submit-btn" class="btn btn-primary">提交</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>
<link rel="stylesheet" href="/stylesheets/jquery-confirm.min-3.2.3.css">
<script src="/multiselect/js/jquery.multi-select.js" type="text/javascript"></script>
<!--<script src="/javascripts/date-extension.js" type="text/javascript"></script>-->
<script src="/javascripts/version-extension.js" type="text/javascript"></script>
<script src="/javascripts/jquery-confirm.min-3.1.1.js"></script>
<script language="JavaScript">

    var robotList = [];

    $('#robots').multiSelect({
        afterSelect: function(value){
            robotList.push(value[0]);
        },
        afterDeselect: function(value){
            var index = robotList.indexOf(value[0]);
            robotList.splice(index,1);
        }
    });

    var editId = null;

    $("#create-btn").click(function () {
        robotList = [];
        $('#name').val('');
        $('#url').val('');
        $('#version').val('');
        $('#robots').multiSelect('deselect_all');
        $("#gituser option").each(function(i,n){
            if($(n).text()==='不使用')
            {
                $(n).attr("selected",true);
            } else  {
                $(n).attr("selected",false);
            }
        })
        $("#repo option").each(function(i,n){
            if($(n).text()==='')
            {
                $(n).attr("selected",true);
            } else  {
                $(n).attr("selected",false);
            }
        })
        $('#myModal').modal('show');

        editId = null;
    })

    function editClick(node) {
        robotList = [];
        var tdNode = node.parentNode.parentNode;
        var id = tdNode.id;

        $('#name').val(document.getElementById('name-' + id).innerText);
        $('#version').val(document.getElementById('version-' + id).innerText);
        var url = $("#name-" + id + ' a').attr('value');
        $('#url').val(url);

//        $('#url').val(document.getElementById('url-' + id));
//        var user = $('#robots').val(document.getElementById('user-' + id).innerText);

//        var robots = document.getElementById('robots-' + id).innerText;
        var robotIdList = [];
        $("#robots-"+id+" li").each(function (i,n) {
            var value = $(n).attr("value");
            robotIdList.push(value);
        })
        var gituserInfo = document.getElementById('gituser-' + id).innerText;

//        var role = $('#role').val();
        $("#gituser option").each(function(i,n){
            if($(n).text()===gituserInfo)
            {
                $(n).attr("selected",true);
            } else  {
                $(n).attr("selected",false);
            }
        })
        var repoInfo = document.getElementById('repo-' + id).innerText;
        $("#repo option").each(function(i,n){
            if($(n).text()===repoInfo)
            {
                $(n).attr("selected",true);
            } else  {
                $(n).attr("selected",false);
            }
        })
        $('#robots').multiSelect('select',robotIdList);

        $('#myModal').modal('show');
        editId = id;
    }

    $("#submit-btn").click(function () {
        var name = $('#name').val();
        var url = $('#url').val();
        var version = $('#version').val();
        var gituser = $('#gituser').val();
        var repo = $('#repo').val();

        var robots = robotList;

        if (name.trim().length === 0) {
            showError('名称不能为空');
            return;
        }
        if (repo.trim().length === 0) {
            showError('Repo不能为空');
            return;
        }
        if (url.trim().length === 0) {
            showError('Git地址不能为空');
            return;
        }
        if (version.trim().length === 0) {
            showError('版本不能为空');
            return;
        }

        var param = {
            name : name,
            url : url,
            version : version,
            gitUser : gituser,
            repo : repo,
            robots : JSON.stringify(robots)
        };

        console.log(param);
        if (editId) {
            param.id = editId;
            $.post("/component/edit",param, function(data) {
                if (data.code === 0) {
                    $('#myModal').modal('hide');
                    showSuccess('已更新模块 ' + name);
                    loadComponentList();
                } else  {
                    showError(data.message);
                }
            });
        } else  {
            $.post("/component/add",param, function(data) {
                if (data.code === 0) {
                    $('#myModal').modal('hide');
                    showSuccess('已添加模块 ' + name);
                    loadComponentList();
                } else  {
                    showError(data.message);
                }
            });
        }
    })

    $(function () {
        loadComponentList();
    })

    function loadComponentList() {
        $.post("/component/list",function (data) {
            console.log(JSON.stringify(data));
            if (data.code == 0) {
                var parent = document.getElementById('list-body');
                for (var i = parent.children.length - 1; i >= 0; i--) {
                    parent.removeChild(parent.children[i]);
                }
                for (var i = 0 ; i < data.data.length ; i++) {
                    var component = data.data[i];
                    var componentNode = document.createElement('tr');
                    var id = component._id;

                    componentNode.id = id;
                    var nameNode = document.createElement('td');
                    nameNode.id = 'name-' + id;
                    nameNode.innerHTML = "<a target='_blank' href='" + component.url + "' value='" + component.url + "'>" + component.name + "</a>";

//                    var urlNode = document.createElement('td');
//                    urlNode.id = 'url-' + id;
//                    urlNode.innerHTML = "<a target='_blank' href='" + component.url + "' value='" + component.url + "'>点击查看</a>";

                    var versionNode = document.createElement('td');
                    versionNode.id = 'version-' + id;
                    versionNode.innerText = component.version;

                    var gituserNode = document.createElement('td');
                    gituserNode.innerText = component.gitUser ? component.gitUser.name : '无';
                    gituserNode.id = 'gituser-' + id;
                    gituserNode.style.display = 'none';

                    var repoNode = document.createElement('td');
                    repoNode.innerText = component.repo ? component.repo.name : '无';
                    repoNode.id = 'repo-' + id;

                    var lastTimeNode = document.createElement('td');
                    lastTimeNode.innerText = component.lastUpdateTime;

                    var lastResultNode = document.createElement('td');
                    lastResultNode.innerText = component.lastUpdateSuccess ? '成功' : '失败';

                    var lastUserNode = document.createElement('td');
                    lastUserNode.innerText = component.lastUpdateUser ? component.lastUpdateUser.nickname : '未知用户';

//                    var robotsNode = document.createElement('td');
//                    robotsNode.id = 'robots-' + id;
//                    robotsNode.innerText = component.robots;

                    var spendNode = document.createElement('td');
                    spendNode.innerText = component.updateSpend + '秒';

                    var robotsNode = document.createElement('td');
//                    robotsNode.innerText = component.robots;
                    var robotHTML = '<ul style="list-style-type:none;padding-left: 0px">';
                    component.robots.forEach(function (robot) {
                        var add = '<li value="' + robot._id + '">' + robot.name + '</li>';
                        robotHTML += add;
                        console.log(add);
                    })
                    robotHTML += '</ul>'
                    robotsNode.id = 'robots-' + id;
                    robotsNode.innerHTML = robotHTML;

                    var  editNode = document.createElement('td');
                    if (component.updating) {
                        editNode.innerHTML = "<a class='btn btn-default' onclick='editClick(this)'>编辑</a>&nbsp;&nbsp;<a id=\"" + id + "\"class='btn btn-warning' onclick='updateProgressClick(this)'>查看</a>";
                    } else {
                        editNode.innerHTML = "<a class='btn btn-default' onclick='editClick(this)'>编辑</a>&nbsp;&nbsp;<a id=\"" + id + "\"class='btn btn-success' onclick='confirmToUpdate(this)'>升级</a>";
                    }

                    componentNode.appendChild(nameNode);
                    componentNode.appendChild(versionNode);
                    componentNode.appendChild(repoNode);
                    componentNode.appendChild(gituserNode);
                    componentNode.appendChild(lastTimeNode);
                    componentNode.appendChild(lastUserNode);
                    componentNode.appendChild(lastResultNode);
                    componentNode.appendChild(spendNode);
                    componentNode.appendChild(robotsNode);
                    componentNode.appendChild(editNode);

                    parent.appendChild(componentNode);
                }

            } else  {

            }
        })
    }
    
    function confirmToUpdate(node) {
        var id = $(node).attr('id');
        var name = document.getElementById('name-' + id).innerText;
        var version = document.getElementById('version-' + id).innerText;
//        var url = document.getElementById('url-' + id).innerText;

        console.log(new Version(version));
//        return;
//        $.confirm({
//            confirmButton: 'Yes i agree',
//            cancelButton: 'NO never !',
//            confirmButtonClass: 'btn-info',
//            cancelButtonClass: 'btn-danger'
//        });

        $.confirm({
            title: '确定要升级' + name + "?",
            content: name + '将升级到' + new Version(version).next(),
            animationBounce: 1.5,
            animation: 'rotateXR',
            closeAnimation: 'rotateYR',
            buttons: {
                ok: {
                    text: "确定",
                    btnClass: 'btn-success',
                    keys: ['enter'],
                    action: function(){
                        loadDelegaters(id, function (data) {
                            $.confirm({
                                title: '请选择代理机',
                                content: '升级需要代理机才可以使用',
                                animationBounce: 1.5,
                                animation: 'rotateXR',
                                closeAnimation: 'rotateYR',
                                buttons: data
                            });
                        })
                    }
                },
                cancel: {
                    text: "取消",
                    action:function(){

                    }
                }
            }
        });
    }

    function loadDelegaters(id,callback) {
        $.post('/component/delegater/list',function (data) {
            if (data.code === 0) {
                var delegaters = data.data;
                if (delegaters && delegaters.length >0) {
                    var list = {};
                    delegaters.forEach(function (delegater,index) {
                        list[index] = {
                            text: delegater.name,
                            btnClass: 'btn-success',
                            keys: ['enter'],
                            action: function () {
                                updateComponent(id,delegater._id);
                            }
                        }
                    })
                    list.cancel = {
                        text: "取消",
                            action:function(){
                        }
                    }
                    callback(list);
                } else {
                    var list = {
                        none : {
                            text: '暂无可用代理机',
                            btnClass: 'btn-success',
                            keys: ['enter'],
                            action: function () {

                            }
                        },
                        cancel: {
                            text: "取消",
                            action:function(){

                            }
                        }
                    }
                    callback(list)
                }
            } else {
                var list = {
                    none: {
                        text: '暂无可用代理机',
                        btnClass: 'btn-success',
                        keys: ['enter'],
                        action: function () {

                        }
                    },
                    cancel: {
                        text: "取消",
                        action:function(){

                        }
                    }
                }
                callback(list)
            }
        })
    }

    function updateComponent(comId,delId) {
        console.log('id ' + comId);
        $.post("/component/update",{com_id:comId,del_id:delId}, function(data) {
            if (data.code === 0) {
                // 开始升级
                // 提示点击查看
                $.confirm({
                    title: '已经开始升级' + data.data.name,
                    content: '是否要查看当前进度？',
                    animationBounce: 1.5,
                    animation: 'rotateXR',
                    closeAnimation: 'rotateYR',
                    buttons: {
                        ok: {
                            text: "去看看",
                            btnClass: 'btn-success',
                            keys: ['enter'],
                            action: function(){
                                loadComponentList();
                                // 跳转
                                updateProgress(comId);
                            }
                        },
                        cancel: {
                            text: "先不了",
                            action:function(){
                                loadComponentList();
                            }
                        }
                    }
                });

            } else  {
                showError(data.message);
            }
        });
    }

    function updateProgressClick(node) {
        var id = $(node).attr('id');
        updateProgress(id);
    }

    function updateProgress(id) {
        window.open('/component/update/' + id);

    }
</script>